package com.ensibs.nuitinfo2013.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.LinkedList;

import android.os.Environment;

public class CollectionPersonnelle extends LinkedList<Integer> implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	private static CollectionPersonnelle instance = null;
	
	public static CollectionPersonnelle getInstance() {
		if (instance == null){
			String path = Environment.getExternalStorageDirectory().getAbsolutePath();
			File file = new File(path+"/nuitinfo/personnalTopic");
			if(file.exists()){
				try {
					FileInputStream fis = new FileInputStream (new File(path+"/nuitinfo/personnalTopic"));
					ObjectInputStream is = new ObjectInputStream(fis);
					CollectionPersonnelle collection = (CollectionPersonnelle) is.readObject();
					is.close();
					instance = collection;
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (StreamCorruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else{
				instance = new CollectionPersonnelle();
			}
		}
		return instance;
	}
	
	
	private CollectionPersonnelle() {
		super();
	}
	
	@Override
	public boolean add(Integer integer){
		boolean tmp = super.add(integer);
		if(tmp){
			String path = Environment.getExternalStorageDirectory().getAbsolutePath();
			File file = new File(path+"/nuitinfo/");
			if(!file.exists()){
				file.mkdir();
			}
			try {
					FileOutputStream fos = new FileOutputStream(new File(path+"/nuitinfo/personnalTopic"));
					ObjectOutputStream os = new ObjectOutputStream(fos);
					os.writeObject(instance);
					os.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (StreamCorruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
		}
		return tmp;
	}
}
